package com.youwe1.wiki.controller;

import com.youwe1.wiki.req.DocQueryReq;
import com.youwe1.wiki.req.DocSaveReq;
import com.youwe1.wiki.resp.CommonResp;
import com.youwe1.wiki.resp.DocQueryResp;
import com.youwe1.wiki.resp.PageResp;
import com.youwe1.wiki.service.DocService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/doc")
public class DocController {

    @Resource
    private DocService docService;

    // 查询个文档
    @GetMapping("/{id}")
    public CommonResp<List<DocQueryResp>> findById(@PathVariable Long id) {
        CommonResp<List<DocQueryResp>> resp = new CommonResp<>();
        List<DocQueryResp> list = docService.findById(id);
        resp.setContent(list);
        return resp;
    }

    // 查询全部文档
    @GetMapping("/all")
    public CommonResp<List<DocQueryResp>> all() {
        CommonResp<List<DocQueryResp>> resp = new CommonResp<>();
        List<DocQueryResp> list = docService.all();
        resp.setContent(list);
        return resp;
    }

    // 查询全部文档分页
    @GetMapping("/list")
    public CommonResp<PageResp<DocQueryResp>> list(@Valid DocQueryReq req) {
        CommonResp<PageResp<DocQueryResp>> resp = new CommonResp<>();
        PageResp<DocQueryResp> list = docService.list(req);
        resp.setContent(list);
        return resp;
    }

    // 新增或编辑
    @PostMapping("/save")
    public CommonResp<Object> save(@Valid @RequestBody DocSaveReq req) {
        CommonResp<Object> resp = new CommonResp<>();
        docService.save(req);
        resp.setMessage("操作成功"); // 设置响应消息
        return resp;
    }

    // 删除文档
    @DeleteMapping("/delete/{idsStr}")
    public CommonResp<Object> delete(@PathVariable String idsStr) {
        CommonResp<Object> resp = new CommonResp<>();
        String[] idArray = idsStr.split(",");
        List<Long> ids = new ArrayList<>();
        for (String id : idArray) {
            ids.add(Long.parseLong(id));
        }
        docService.delete(ids);
        resp.setMessage("操作成功"); // 设置响应消息
        return resp;
    }

    // 查询文档的内容
    @GetMapping("/findContent/{id}")
    public CommonResp<String> findContent(@PathVariable Long id) {
        CommonResp<String> resp = new CommonResp<>();
        String content = docService.findContent(id);
        resp.setContent(content);
        return resp;
    }

    @GetMapping("/vote/{id}")
    public CommonResp<Object> vote(@PathVariable Long id){
        CommonResp<Object> resp = new CommonResp<>();
        docService.vote(id);
        resp.setMessage("操作成功"); // 设置响应消息
        return resp;
    }
}
